#include "chartsdemo01.h"

#include "ui_chartsdemo01.h"

// #include <QStandardItemModel>
#include <QIntValidator>
#include <QLayout>
#include <QMenu>
#include <QMessageBox>
#include <QStringList>
#include <QStyledItemDelegate>
#include <QValueAxis>
#include <QVector>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include <algorithm>

static const QStringList KTableHeader{"X(int)", "Y(float)"};

ChartsDemo01::ChartsDemo01(QWidget *parent)
    : QWidget(parent), ui(new Ui::ChartsDemo01) {
    ui->setupUi(this);

    // 设置表头
    ui->dataTabWidget->setColumnCount(KTableHeader.count());
    ui->dataTabWidget->setHorizontalHeaderLabels(KTableHeader);
    // 设置表格可以使用双击的当时进行编辑模式
    ui->dataTabWidget->setEditTriggers(QAbstractItemView::DoubleClicked);
    ui->dataTabWidget->setRowCount(3);

    // 设置右键菜单模式
    ui->dataTabWidget->setContextMenuPolicy(Qt::CustomContextMenu);

    connect(ui->dataTabWidget, &QTableWidget::customContextMenuRequested,
            [=](const QPoint &pos) {
                QMenu    menu;
                QAction *addAction = menu.addAction("添加行");
                connect(addAction, &QAction::triggered, [=] {
                    if (ui->dataTabWidget->rowCount() == 0)
                        ui->dataTabWidget->setRowCount(1);
                    else
                        ui->dataTabWidget->insertRow(
                            ui->dataTabWidget->currentRow() + 1);
                });
                QAction *removeAction = menu.addAction("删除行");
                connect(removeAction, &QAction::triggered, [=] {
                    // FIXME 表中删除了行，但是数据并没有删除
                    if (ui->dataTabWidget->rowCount() > 0)
                        ui->dataTabWidget->removeRow(
                            ui->dataTabWidget->currentRow());
                });
                menu.exec(ui->dataTabWidget->viewport()->mapToGlobal(pos));
            });

    //
    chart_  = new QChart();
    series_ = new QLineSeries();
    chart_->addSeries(series_);
    // 创建x轴，
    QValueAxis *xAxis = new QValueAxis();
    xAxis->setRange(0, 100);
    // FIXWME 将x坐标轴设置为以10为间隔
    xAxis->setTickInterval(10);
    xAxis->setLabelFormat("%d");
    chart_->addAxis(xAxis, Qt::AlignBottom);
    series_->attachAxis(xAxis);
    QValueAxis *yAxis = new QValueAxis();
    yAxis->setRange(0, 1.0);
    chart_->addAxis(yAxis, Qt::AlignLeft);
    series_->attachAxis(yAxis);

    view_ = new QChartView();
    view_->setChart(chart_);
    view_->setRenderHint(QPainter::Antialiasing);  // 开启反锯齿

    QVBoxLayout *layout = new QVBoxLayout(ui->chartWidget);
    layout->addWidget(view_);

    // TODO 增加图表缩放功能
    // TODO 增加按钮控制图表显示模式功能
}

ChartsDemo01::~ChartsDemo01() { delete ui; }

void ChartsDemo01::on_dataTabWidget_cellChanged(int row, int column) {
    auto item = ui->dataTabWidget->item(row, column);
    if (0 == column && !item->text().toInt()) {
        // BUG toInt失败时返回0，如果输入为0时，会误判为不是整数
        QMessageBox::warning(this, "错误", "请输入一个整数");
        item->setBackground(Qt::red);
        return;
    } else if (1 == column && !item->text().toFloat()) {
        QMessageBox::warning(this, "错误", "请输入一个浮点数");
        item->setBackground(Qt::red);
        return;
    } else {
        item->setBackground(Qt::white);
    }
    ui->dataTabWidget->sortItems(0);
    if (data_.xAxis.size() < ui->dataTabWidget->rowCount())
        data_.xAxis.resize(ui->dataTabWidget->rowCount());
    if (data_.yAxis.size() < ui->dataTabWidget->rowCount())
        data_.yAxis.resize(ui->dataTabWidget->rowCount());
    if (0 == column)
        data_.xAxis[row] = item->text().toInt();
    else if (1 == column)
        data_.yAxis[row] = item->text().toFloat();
    return;
}

void ChartsDemo01::on_updateChartBtn_clicked() {
    // 先更新坐标轴，再更新数据
    auto min = *std::min_element(data_.yAxis.begin(), data_.yAxis.end());
    auto max = *std::max_element(data_.yAxis.begin(), data_.yAxis.end());
    // FIXME 解决y轴无法覆盖最值的问题
    chart_->axes()[1]->setRange(min, max);
    if (data_.xAxis.count() > 0 && data_.xAxis.count() == data_.yAxis.count()) {
        series_->clear();
        for (int i = 0; i < data_.xAxis.size(); ++i)
            series_->append(data_.xAxis[i], data_.yAxis[i]);
    }
}
